package cn.bb.dao;


import cn.bb.pojo.Person;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao {
    @Override
    public List<Person> searchPerson(String hql) {
        return getHibernateTemplate().find(hql);
    }

    @Override
    public List<Person> searchPerson(Person person) {
        List<Person> list = getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                //构建查询
                Criteria criteria = session.createCriteria(Person.class);
                //构建查询条件的代码
                if(criteria != null){
                    if(person.getUsername() != null && person.getUsername().trim().length() >0){
                        criteria.add(Restrictions.like("username",person.getUsername(), MatchMode.ANYWHERE));
                    }
                }
                return criteria.list();
            }
        });
        return list;
    }

    @Override
    public Person get(int id) {
        return getHibernateTemplate().get(Person.class,id);
    }

    @Override
    public void addPerson(Person person) {
        getHibernateTemplate().save(person);
    }

    @Override
    public void updatePerson(Person person) {
        getHibernateTemplate().update(person);
    }

    @Override
    public void delPerson(int id) {
        getHibernateTemplate().delete(this.get(id));
    }
}
